package com.example.demo.controller.data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BillAnalysisService {

    @Autowired
    private ExcelService excelService;


    @Autowired
    private DataImportService dataImportService;
    // 添加支持时间参数的analyzeBill方法
    public byte[] analyzeBill(MultipartFile file, Date startTime, Date endTime) throws IOException {
        // 1. 读取Excel数据（正向账单）
        List<BillDataDto> billDataList = excelService.readExcel(file);

        // 2. 读取退款数据
        List<RefundDataDto> refundDataList = excelService.readRefundExcel(file);

        // 3. 按核销人昵称分组（正向账单）
        Map<String, List<BillDataDto>> groupedByNickname = billDataList.stream()
                .collect(Collectors.groupingBy(BillDataDto::getNickname));

        // 4. 按核销人昵称分组（退款数据）
        Map<String, List<RefundDataDto>> refundGroupedByNickname = refundDataList.stream()
                .collect(Collectors.groupingBy(RefundDataDto::getNickname));

        // 5. 构建分析结果
        List<AnalysisResultDto> results = new ArrayList<>();

        // 合并正向和退款数据的所有昵称
        Set<String> allNicknames = new HashSet<>();
        allNicknames.addAll(groupedByNickname.keySet());
        allNicknames.addAll(refundGroupedByNickname.keySet());

        for (String nickname : allNicknames) {
            AnalysisResultDto result = new AnalysisResultDto();
            result.setNickname(nickname);

            // 处理正向账单数据
            if (groupedByNickname.containsKey(nickname)) {
                List<BillDataDto> dataList = groupedByNickname.get(nickname);

                // 按内容渠道分组
                Map<String, List<BillDataDto>> groupedByChannel = dataList.stream()
                        .collect(Collectors.groupingBy(BillDataDto::getChannel));

                groupedByChannel.forEach((channel, channelDataList) -> {
                    // 按订单商品分组
                    Map<String, List<BillDataDto>> groupedByProduct = channelDataList.stream()
                            .collect(Collectors.groupingBy(BillDataDto::getProduct));

                    Map<String, AnalysisResultDto.ChannelProductStats> productStatsMap =
                            result.getChannelProductMap().computeIfAbsent(channel, k -> new LinkedHashMap<>());

                    groupedByProduct.forEach((product, productDataList) -> {
                        AnalysisResultDto.ChannelProductStats stats = new AnalysisResultDto.ChannelProductStats();
                        stats.setCount(productDataList.size());
                        stats.setAmount(productDataList.stream().mapToDouble(BillDataDto::getAmount).sum());
                        stats.setInCome(productDataList.stream().mapToDouble(BillDataDto::getInCome).sum());
                        productStatsMap.put(product, stats);

                        // 累加总计
                        result.setTotalCount(result.getTotalCount() + stats.getCount());
                        result.setTotalAmount(result.getTotalAmount() + stats.getAmount());
                        result.setTotalIncomeAmount(result.getTotalIncomeAmount() + stats.getInCome());

                    });
                });
            }

            // 处理退款数据
            if (refundGroupedByNickname.containsKey(nickname)) {
                List<RefundDataDto> refundList = refundGroupedByNickname.get(nickname);

                // 按内容渠道分组
                Map<String, List<RefundDataDto>> groupedByChannel = refundList.stream()
                        .collect(Collectors.groupingBy(RefundDataDto::getChannel));

                groupedByChannel.forEach((channel, channelDataList) -> {
                    // 按订单商品分组
                    Map<String, List<RefundDataDto>> groupedByProduct = channelDataList.stream()
                            .collect(Collectors.groupingBy(RefundDataDto::getProduct));

                    Map<String, AnalysisResultDto.ChannelProductStats> productStatsMap =
                            result.getRefundChannelProductMap().computeIfAbsent(channel, k -> new LinkedHashMap<>());

                    groupedByProduct.forEach((product, productDataList) -> {
                        AnalysisResultDto.ChannelProductStats stats = new AnalysisResultDto.ChannelProductStats();
                        stats.setCount(productDataList.size());
                        stats.setAmount(productDataList.stream().mapToDouble(RefundDataDto::getActualPayment).sum());
                        stats.setInCome(productDataList.stream().mapToDouble(RefundDataDto::getInCome).sum());
                        productStatsMap.put(product, stats);

                        // 累加总计
                        result.setTotalRefundCount(result.getTotalRefundCount() + stats.getCount());
                        result.setTotalRefundAmount(result.getTotalRefundAmount() + stats.getAmount());

                        result.setReturnIncomeAmount(result.getReturnIncomeAmount() + stats.getInCome());
                    });
                });
            }

            results.add(result);
        }

        // 6. 生成Excel文件
        return excelService.generateAnalysisResult(results);
    }



}